#include "Plane.h"
#include "Ray.h"
#include "DXUtil.h"
#include <d3dx9.h>
#include <d3d9.h>
#include <math.h>

//bool Sphere::Intersect(D3DXVECTOR3 ray)
//{
//	return false;
//}

float Plane::Intersect(RAY &ray) {
	
	float denom = D3DXVec3Dot(&D3DXVECTOR3(0,1,0), &ray.direction);
	/*if(denom < 0)
	{
		denom *= -1.0f;
	}*/

    if (denom < 1.4f*(10^-45))
    {
        return -1;
    }
    else
    {
		float nom = D3DXVec3Dot(&D3DXVECTOR3(0,1,0), &ray.origin) + Distance;
        float t = -(nom / denom);

        if (t >= 0)
		{
			D3DXVECTOR3 pointOnPlane = ray.origin + (ray.direction * t);

			if(pointOnPlane.x <= point.x + Width && pointOnPlane.x >= point.x && pointOnPlane.z <= (point.z + Depth) && pointOnPlane.z >= point.z)
			{
				return t;
			}
			else
			{
				return -1.0f;
			}
		
          
		}	
        return -1.0f;
    }
}

void Plane::GetColor(D3DXCOLOR* pColor, D3DXVECTOR3* intersectionPoint)
{
	D3DXVECTOR2 uv = D3DXVECTOR2();
	uv.x = (this->point.x - intersectionPoint->x);
	uv.y = (this->point.y - intersectionPoint->z);

	switch(TEXTURE)
	{
	case 0:
		if(((int)uv.x % 2 == 0 && (int)uv.y % 2 == 0) ||
			((int)uv.x % 2 != 0 && (int)uv.y % 2 != 0))
		{
			pColor->r = 255;
			pColor->g = 0;
			pColor->b = 0;
		}
		else
		{
			pColor->r = 255;
			pColor->g = 255;
			pColor->b = 0;
		}
		break;
	
	case 1:

		float distance = sqrt(((uv.x - textureCenter.x) * (uv.x - textureCenter.x)) + ((uv.y - textureCenter.y) * (uv.y - textureCenter.y)));
		if((int)distance % 2 == 0)
		{
			pColor->r = 255;
			pColor->g = 0;
			pColor->b = 0;
		}
		else
		{
			pColor->r = 0;
			pColor->g = 255;
			pColor->b = 0;
		}
		break;
	}
}
